var tp_arr = new Array(
    "/static/app/transverse/system/auth02/dispatch/index.htm",
    "/static/app/transverse/plugins/poup_write_off_cw.htm",
    "/static/app/transverse/plugins/poup_print_cw.htm"
);
var keywordStr = window.getUrlParam("k");
var planDate = window.getUrlParam("pd");
var startDate = window.getUrlParam("sd");
var endDate = window.getUrlParam("nd");
var cw = window.getUrlParam("cw");
var ct = window.getUrlParam("ct");
var wg = window.getUrlParam("wg");
var pageNo = window.getUrlParam("p");
var totle = window.getUrlParam("t");
window.current = new Vue({
    el: '#current',
    template: window.getTemplate(tp_arr),
    data: {
        pages: [],
        totle: totle ? totle : 0,
        page: pageNo ? parseInt(pageNo) : 1,
        toPage: pageNo ? parseInt(pageNo) : 1,
        size: 10,
        keyword: keywordStr ? keywordStr : '',
        cw: cw ? cw : '0',
        ct: ct ? ct : '0',
        wg: wg ? wg : '0',
        planDate: planDate ? planDate : window.getDateNow(),
        startDate: startDate ? startDate : '',
        endDate: endDate ? endDate : '',
        moList: [],
        moInfo: {},
        fQtyCW: 0,
        fProcessCW: ''
    },
    // 属性监听器
    watch: {},
    filters: {
        _formatDate: function (val) {
            return window.dateTimeFormat(val, "yyyy-MM-dd");
        },
        _formatDateTime: function (val) {
            return window.dateTimeFormat(val, "yyyy-MM-dd h:m:s");
        },
        _getDiwShow: function (planDate) {
            var startDate = window.current['startDate'];
            var endDate = window.current['endDate'];
            startDate = startDate ? startDate : '';
            endDate = endDate ? endDate : '';
            var className = ['input-group'];
            if(startDate != '' || endDate != ''){
                className.push('display-none');
            }
            return className;
        },
        _getBgColor: function (index) {
            var info = window.current['moList'][index];
            var fPlanCountCw = parseInt(info['fPlanCountCw']);
            //var fStep02 = parseInt(info['fStep02']);
            var className = '';
            if(fPlanCountCw > 0){
                className = 'red-bg';
            }
            return className;
        },
        _getRowsColor: function (index) {
            var className = 'even';
            if(index % 2 == 0){
                className = '';
            }
            return className;
        },
        _formatNumber: function (val) {
            val = parseInt(val);
            if(isNaN(val)){
                val = 0;
            }
            return val;
        },
        _currPage: function (val) {
            var page = window.current['page'];
            var pages = window.current['pages'].length;
            val = parseInt(val);
            var className = [];
            if(pages > 9 && page <= 5 && val > 9){
                className.push('display-none');
            }else if(pages > 9 && (pages - page < 5)){
                if(pages - val >= 9) {
                    className.push('display-none');
                }
            }else if(pages > 9 && page > 5 && (val < page - 4 || val > page + 4)){
                className.push('display-none');
            }
            /*if(pages > 9 && page > 5 && ((page - 4 > val) || (page + 4 < val))){
                className.push('display-none');
            }*/
            if(page == val){
                className.push('active');
            }
            return className;
        },
        _currPageLeft: function () {
            var page = window.current['page'];
            var pagesArr = window.current['pages'];
            var pages = pagesArr?pagesArr.length:0;
            var className = [];
            if(!(pages > 9 && page > 5)){
                className.push('display-none');
            }
            return className;
        },
        _currPageRight: function () {
            var page = window.current['page'];
            var pagesArr = window.current['pages'];
            var pages = pagesArr?pagesArr.length:0;
            var className = [];
            if(pages <= 9 || (pages - page < 5)){
                className.push('display-none');
            }
            return className;
        }
    },
    computed: {},
    methods: {
        onSearch: function () {
            var keyword = this['keyword'];
            var planDate = this['planDate'];
            var startDate = this['startDate'];
            var endDate = this['endDate'];
            var hrefStr =  window.location.pathname + '?a=1';
            if(keyword != ''){
                hrefStr += '&k=' + keyword;
            }
            if(planDate != ''){
                hrefStr += '&pd=' + planDate;
            }
            if(startDate != ''){
                hrefStr += '&sd=' + startDate;
            }
            if(endDate != ''){
                hrefStr += '&nd=' + endDate;
            }
            //console.log(hrefStr);return;
            window.location.href = hrefStr;
        },
        onSetPage: function (val) {
            var page = this['page'];
            var totle = this['totle'];
            var keyword = this['keyword'];
            var planDate = this['planDate'];
            var startDate = this['startDate'];
            var endDate = this['endDate'];
            if(page != val){
                var hrefStr =  window.location.pathname + '?a=1';
                if((keywordStr == null && keyword == '')|| keywordStr == keyword){
                    hrefStr += '&p=' + val + '&t=' + totle;
                }
                if(keyword != ''){
                    hrefStr += '&k=' + keyword;
                }
                if(planDate != ''){
                    hrefStr += '&pd=' + planDate;
                }
                if(startDate != ''){
                    hrefStr += '&sd=' + startDate;
                }
                if(endDate != ''){
                    hrefStr += '&nd=' + endDate;
                }
                if(cw != ''){
                    hrefStr += '&cw=' + cw;
                }
                if(ct != ''){
                    hrefStr += '&ct=' + ct;
                }
                if(wg != ''){
                    hrefStr += '&wg=' + wg;
                }
                window.location.href = hrefStr;
            }
        },
        onToPage: function () {
            var page = this['page'];
            var to_page = this['toPage'];
            var totle = this['totle'];
            var keyword = this['keyword'];
            var planDate = this['planDate'];
            var startDate = this['startDate'];
            var endDate = this['endDate'];
            var pagesArr = this['pages'];
            var cw = this['cw'];
            var ct = this['ct'];
            var wg = this['wg'];
            var pages = pagesArr?pagesArr.length:0;
            if(to_page > pages){
                window.custom_toast('无法跳转该页面！');return;
            }
            if(page != to_page){
                var hrefStr =  window.location.pathname + '?a=1';
                if((keywordStr == null && keyword == '')|| keywordStr == keyword){
                    hrefStr += '&p=' + to_page + '&t=' + totle;
                }
                if(keyword != ''){
                    hrefStr += '&k=' + keyword;
                }
                if(planDate != ''){
                    hrefStr += '&pd=' + planDate;
                }
                if(startDate != ''){
                    hrefStr += '&sd=' + startDate;
                }
                if(endDate != ''){
                    hrefStr += '&nd=' + endDate;
                }
                if(cw != ''){
                    hrefStr += '&cw=' + cw;
                }
                if(ct != ''){
                    hrefStr += '&ct=' + ct;
                }
                if(wg != ''){
                    hrefStr += '&wg=' + wg;
                }
                window.location.href = hrefStr;
            }
        },
        onToAgentDetail: function (index) {
            var info = this['moList'][index];
            var rf_url = window.location.pathname + window.location.search;
            var url = "/system/Auth03/detail.html?c=" + info['agency_code'] + "&rf=" + encodeURIComponent(rf_url);

            window.location.href = url;
        },
        onMoreMoList: function () {
            var page = this['page'];
            var size = this['size'];
            var totle = this['totle'];
            if(page * size < totle){
                window.get_mo_list_more();
            }
        },
        onConfirmWriteOff: function (index) {
            var moList = this['moList'];
            var moInfo = moList[index];
            var fQtyCW = moInfo['fQtyCW'];
            var fProcessCW = moInfo['fProcessCW'];
            this['fQtyCW'] = fQtyCW;
            this['fProcessCW'] = fProcessCW;
            this['moInfo'] = moInfo;
            window.poup('#write_off_cw_poup');
        },
        onWriteOff: function () {
            window.sub_write_off();
        },
        onUnWriteOff: function (index) {
            window.sub_un_write_off(index);
        },
        onConfirmExportExcel: function (index) {
            var moList = this['moList'];
            var moInfo = moList[index];
            var fProcessCW = moInfo['fProcessCW'];
            var fQtyCW = parseInt(moInfo['fMoQty']);
            this['fProcessCW'] = fProcessCW;
            this['fQtyCW'] = fQtyCW;
            this['moInfo'] = moInfo;
            window.poup('#print_cw_poup');
        },
        onRefresh: function () {
            //_currPageRightwindow.location.reload();
            window.get_mo_list_to_page_one();
        },
        onRadioChecked: function (key, val) {
            var totle = this['totle'];
            var keyword = this['keyword'];
            var planDate = this['planDate'];
            var startDate = this['startDate'];
            var endDate = this['endDate'];
            var cw = this['cw'];
            var ct = this['ct'];
            var wg = this['wg'];
            if(this[key] != val){
                switch (key) {
                    case 'cw':
                        cw = val;
                        break;
                    case 'ct':
                        ct = val;
                        break;
                    case 'wg':
                        wg = val;
                        break;
                }
                var hrefStr =  window.location.pathname + '?a=1';
                if(keyword != ''){
                    hrefStr += '&k=' + keyword;
                }
                if(planDate != ''){
                    hrefStr += '&pd=' + planDate;
                }
                if(startDate != ''){
                    hrefStr += '&sd=' + startDate;
                }
                if(endDate != ''){
                    hrefStr += '&nd=' + endDate;
                }
                if(cw != ''){
                    hrefStr += '&cw=' + cw;
                }
                if(ct != ''){
                    hrefStr += '&ct=' + ct;
                }
                if(wg != ''){
                    hrefStr += '&wg=' + wg;
                }
                window.location.href = hrefStr;
            }
        },
        onSubEideMoInfo: function (index) {
            //var info = this['moList'][index];
            window.sub_edit_mo_info(index);
        },
        onExportExcel: function () {
            window.export_excel();
        },
        onOpenUploadExcel: function () {
            $('#uploadExcel').click();
        },
        onUploadExcel: function () {
            //var src, url = window.URL || window.webkitURL || window.mozURL；
            var files = event.target.files;
            var number = 5;
            var max_size = 1024 * 1024 * number;
            if(files.length > 1){
                window.custom_toast('抱歉，只支持单个文件上传！');return;
            }
            var file = files[0];
            if(file.size > max_size){
                window.custom_toast('抱歉你上传的文件大于【' + number + 'M】，请处理后再上传！');return;
            }
            window.loading();
            var form = $('#importExcelForm');
            form.submit();
        },
        onPrintPDF: function () {
            window.export_pdf();
        }
    }
});

window.get_mo_list_to_page_one = function () {
    window.current['page'] = 1;
    window.current['moList'] = [];
    window.current['totle'] = 0;
    window.get_mo_list();
}

window.get_mo_list_more = function () {
    var page = window.current['page'];
    window.current['page'] = parseInt(page) + 1;
    window.get_mo_list();
}

window.get_mo_list = function () {
    var keyword = window.current['keyword'];
    var planDate = window.current['planDate'];
    var startDate = window.current['startDate'];
    var endDate = window.current['endDate'];
    var cw = window.current['cw'];
    var ct = window.current['ct'];
    var wg = window.current['wg'];
    var page = window.current['page'];
    var size = window.current['size'];

    if((startDate == '' && endDate != '') || (startDate != '' && endDate == '')){
        window.custom_toast('开令开始时间与开令结束时间同时为必选！');return;
    }else {
        if(planDate == ''){
            window.custom_toast('计划生产交期日期为必选！');return;
        }
    }

    var data_arr = {
        keyword : keyword,
        fPlanDate : planDate,
        fStartDate : startDate,
        fEndDate : endDate,
        cw : cw,
        ct : ct,
        wg : wg,
        page: page,
        size: size
    };
    window.ajax({
        url: "/service/Dispatch/getMoList",
        data: data_arr,
        async: false,
        success: function (d) {
            if (d['status'] == 1) {
                var totle = window.current['totle'];
                var moList = window.current['moList'];
                var list = d['data'];
                if (list) {
                    $.each(list, function(i, info) {
                        var fPlanCountCw = parseInt(info['fPlanCountCw']) - parseInt(info['fStep02']);
                        info['fPlanCountCw'] = fPlanCountCw < 0 ? 0 : fPlanCountCw;
                        moList.push(info);
                    });
                    //window.current['moList'] = moList;
                    if (totle == 0) {
                        window.get_mo_list_count();
                    }
                    window.get_not_used_cw(moList);
                }
            } else {
                window.custom_toast(d['msg']);
            }
        }
    });
}

window.get_not_used_cw = function (moList) {
    var data_arr = {};
    window.ajax({
        url: "/service/Dispatch/getNotUseCW",
        data: data_arr,
        async: false,
        success: function (d) {
            if (d['status'] == 1) {
                var stock = d['data'];
                if (stock) {
                    $.each(moList, function(i, info) {
                        var fModelCodeCW = info['fModelCodeCW'];
                        var fQtyCW = 0;
                        if(fModelCodeCW != null){
                            var planID = '#plan_' + i;
                            var btnID = '#btn_' + i;
                            if(typeof (stock[fModelCodeCW] != 'undefined')) {
                                var stockCount = parseInt(stock[fModelCodeCW]);
                                var plsnCount = parseInt(info['fMoQty']);//fMoQty
                                var currCount = parseInt(info['fStep02']);
                                var differ = plsnCount - currCount;
                                if (differ > 0 && stockCount > 0) {
                                    if(differ >= stockCount){
                                        fQtyCW = stockCount;
                                        stock[fModelCodeCW] = 0;
                                    }else{
                                        fQtyCW = differ;
                                        stock[fModelCodeCW] = stockCount - differ;
                                    }
                                    $(btnID).show();
                                    $(planID).hide();
                                }
                            }
                            //$(planID).html(curr_val);
                        }
                        moList[i]['fQtyCW'] = fQtyCW;
                    });
                    window.current['moList'] =[];
                    window.current['moList'] = moList;
                }
            } else {
                window.custom_toast(d['msg']);
            }
        }
    });
}

window.get_mo_list_count = function () {
    var keyword = window.current['keyword'];
    var planDate = window.current['planDate'];
    var startDate = window.current['startDate'];
    var endDate = window.current['endDate'];
    var cw = window.current['cw'];
    var ct = window.current['ct'];
    var wg = window.current['wg'];
    var data_arr = {
        keyword : keyword,
        fPlanDate : planDate,
        fStartDate : startDate,
        fEndDate : endDate,
        cw : cw,
        ct : ct,
        wg : wg
    };
    window.ajax({
        url: "/service/Dispatch/getMoListCount",
        data: data_arr,
        async: false,
        success: function (d) {
            if (d['status'] == 1) {
                var totle = parseInt(d['data']);
                if (totle > 0) {
                    window.setPages(totle);
                }
                window.current['totle'] = totle;
            } else {
                window.custom_toast(d['msg']);
            }
        }
    });
}

window.sub_edit_mo_info = function (index) {
    var moList =  window.current['moList'];
    var info =  moList[index];
    if(typeof (info) == 'undefined'){
        window.custom_toast('无法识别当前操作，请刷新页面再试！');return;
    }
    var fMONo = info['fMONo'];
    var fGoodsID = info['fGoodsID'];
    var sort = info['sort'];
    var fMoQty = parseInt(info['fMoQty']);
    var fPlanCountCw = parseInt(info['fPlanCountCw']);
    var fStep02 = parseInt(info['fStep02']);
    if(sort == ''){
        sort = 0;
    }
    if(fPlanCountCw == ''){
        fPlanCountCw = 0;
    }
    if(!(test_number.test(sort))){
        window.custom_toast('排序权重只能为数字！');return;
    }
    if(!(test_number.test(fPlanCountCw))){
        window.custom_toast('床网所需数量只能为数字！');return;
    }
    if((fMoQty - fStep02) < fPlanCountCw){
        window.custom_toast('床网所需数量最大只能为' + (fMoQt - fStep02) + '！');return;
    }
    var data_arr = {
        fMONo : fMONo,
        fGoodsID : fGoodsID,
        sort : sort,
        fPlanCountCw: (fPlanCountCw + fStep02)
    };
    window.ajax({
        url: "/service/Dispatch/editMoInfo",
        data: data_arr,
        async: false,
        loading: false,
        success: function (d) {
            if (d['status'] == 1) {
                var info = d['data'];
                /*if (info) {
                    moList[index] = info;
                    window.current['moList'] = [];
                    window.current['moList'] = moList;
                }*/
            } else {
                window.custom_toast(d['msg']);
            }
        }
    });
}

window.sub_write_off = function (index) {
    var moInfo = window.current['moInfo'];
    var fQtyCW = parseInt(window.current['fQtyCW']);
    if(fQtyCW < 1){
        window.current['fQtyCW'] = 1;
        window.custom_toast('“核销床网数量” 不能小于1！');return;
    }
    if(parseInt(moInfo['fQtyCW']) < fQtyCW ){
        window.current['fQtyCW'] = moInfo['fQtyCW'];
        window.custom_toast('“核销床网数量” 不能大于 “计划床网”！');return;
    }
    var data_arr = {
        fMONo : moInfo['fMONo'],
        fGoodsID : moInfo['fGoodsID'],
        fQtyCW: fQtyCW
    };
    window.ajax({
        url: "/service/Dispatch/toWriteOff",
        data: data_arr,
        async: false,
        success: function (d) {
            if (d['status'] == 1) {
                var info = d['data'];
                if (info) {
                    window.poup_close('#write_off_cw_poup');
                    //window.poup('#print_cw_poup');
                    window.get_mo_list_to_page_one();
                }
            } else {
                window.custom_toast(d['msg']);
            }
        }
    });
}

window.sub_un_write_off = function (index) {
    var moList = window.current['moList'];
    var moFind = moList[index];
    var data_arr = {
        fMONo : moFind['fMONo'],
        fGoodsID : moFind['fGoodsID']
    };
    window.ajax({
        url: "/service/Dispatch/toUnWriteOff",
        data: data_arr,
        async: false,
        success: function (d) {
            if (d['status'] == 1) {
                var info = d['data'];
                if (info) {
                    window.get_mo_list_to_page_one();
                }
            } else {
                window.custom_toast(d['msg']);
            }
        }
    });
}

window.export_excel = function () {
    var keyword = window.current['keyword'];
    var planDate = window.current['planDate'];
    var startDate = window.current['startDate'];
    var endDate = window.current['endDate'];
    var cw = window.current['cw'];
    var ct = window.current['ct'];
    var wg = window.current['wg'];

    var data_arr = {
        keyword : keyword,
        fPlanDate : planDate,
        fStartDate : startDate,
        fEndDate : endDate,
        cw : cw,
        ct : ct,
        wg : wg
    };

    var form = $('#exportExcelForm');
    form.html('');
    $.each(data_arr, function (key, val) {
        var inputHTML = $("<input type='hidden' name='" + key + "'/>");
        inputHTML.attr("value", val);
        form.append(inputHTML);
    });
    form.submit();
}

window.export_pdf = function () {
    var fProcessCW = window.current['fProcessCW'];
    var fQtyCW = window.current['fQtyCW'];
    var moInfo = window.current['moInfo'];
    var fGoodsID = moInfo['fGoodsID'];
    if(fQtyCW < 1){
        window.current['fQtyCW'] = 1;
        window.custom_toast('“打印数量” 不能小于1！');return;
    }
    if(fQtyCW > 999){
        window.current['fQtyCW'] = 999;
        window.custom_toast('“打印数量” 不能大于999！');return;
    }
    var data_arr = {
        fGoodsID : fGoodsID,
        fProcessCW : fProcessCW,
        fQtyCW : fQtyCW
    };

    var form = $('#exportPdfForm');
    form.html('');
    $.each(data_arr, function (key, val) {
        var inputHTML = $("<input type='hidden' name='" + key + "'/>");
        inputHTML.attr("value", val);
        form.append(inputHTML);
    });
    form.submit();
    window.poup_close('#print_cw_poup');
}

window.setPages = function (count) {
    var size = window.current['size'];
    var pageCount = Math.ceil(count / size);
    var pages = [];
    for(let i = 1; i　<= pageCount; i++) {
        pages.push(i);
    }
    window.current['pages'] = pages;
}

window.get_mo_list();

//日期范围限制
var start = {
    elem: '#start',
    format: 'YYYY-MM-DD hh:mm:ss',
    istime: true, //是否开启时间选择
    isclear: true, //是否显示清空
    istoday: false, //是否显示今天
    choose: function (datas) {
        window.current['startDate'] = datas;
    },
    clear: function () {
        window.current['startDate'] = '';
    }
};

var end = {
    elem: '#end',
    format: 'YYYY-MM-DD hh:mm:ss',
    istime: true, //是否开启时间选择
    isclear: true, //是否显示清空
    istoday: false, //是否显示今天
    choose: function (datas) {
        window.current['endDate'] = datas;
    },
    clear: function () {
        window.current['endDate'] = '';
    }
};

var plan = {
    elem: '#plan',
    format: 'YYYY-MM-DD',
    istime: false, //是否开启时间选择
    isclear: false, //是否显示清空
    istoday: false, //是否显示今天
    choose: function (datas) {
        window.current['planDate'] = datas;
    }
};

laydate(plan);
laydate(start);
laydate(end);
